#!/usr/bin/env python3
#! -*- coding: utf-8 -*-

import re
from typing import Dict, List
import requests
import os

TABLE_TEMPLATE = '''<table style="text-align: center">
    <thead>
        <tr>
            <th>架构名称</th>
            <th><code>_arch</code> 宏对应值</th>
            <th>RPM 内部枚举值</th>
        </tr>
    </thead>
    <tbody>
        {tbody}
    </tbody>
</table>
'''

# Path to rpm rpmrc.in
RPMRC_IN_URL = 'https://raw.githubusercontent.com/rpm-software-management/rpm/master/rpmrc.in'
content = requests.get(RPMRC_IN_URL).text.split('\n')
# with open(os.path.join(os.path.dirname(__file__), 'rpmrc.in'), 'r', encoding='utf-8') as f:
#     content = f.read().splitlines()

exp = r'arch_canon:\s*(?P<alias>[^:]+):\s*(?P<name>\S+)\s*(?P<value>\S+)'
patt = re.compile(exp, re.I)

group_dic_lis: List[Dict[str, str]] = list()

for line in content:
    line = line.strip()
    if not line.startswith('arch_canon'):
        continue
    res = re.match(patt, line)
    group_dic_lis.append(res.groupdict())

i = 0
tbody = ''
last_name = None
last_val = None

for i in range(len(group_dic_lis)):
    dic = group_dic_lis[i]
    tr = '<tr>'
    tr += '<td><code>{}</code></td>'.format(dic.get('alias'))

    if dic.get('name') != last_name:
        last_name = dic.get('name')
        j = i + 1
        for j in range(i + 1, len(group_dic_lis)):
            if group_dic_lis[j].get('name') != last_name:
                break
        row_span = j - i
        tr += "<td{}><code>{}</code></td>".format(f' rowspan={row_span}' if row_span > 1 else '', last_name)

    if dic.get('value') != last_val:
        last_val = dic.get('value')
        j = i + 1
        for j in range(i + 1, len(group_dic_lis)):
            if group_dic_lis[j].get('value') != last_val:
                break
        row_span = j - i
        tr += "<td{}><code>{}</code></td>".format(f' rowspan={row_span}' if row_span > 1 else '', last_val)

    tr += '</tr>'
    tbody += tr

final_res = TABLE_TEMPLATE.format(tbody=tbody)
print(final_res)
